package com.leetcode.LC;

import java.util.Arrays;

public class LC1005 {
    public int largestSumAfterKNegations(int[] A, int K) {
        //思路：比较K与负数的数量
        /*
        K小于等于负数的数量--》把前K个数变为正数求和
        K大于负数的数量，并且剩余m个，m为奇数,--》数组存在0则直接求数组每个值的绝对值的和即可，否则对数组重新排序，把最小值改为负数
        K大于负数的数量，并且剩余m个，m为偶数--》求数组每个值的绝对值的和即可
         */
        Arrays.sort(A);
        int count = 0;
        boolean f = false;
        for (int i : A) {
            if (i < 0) {
                count++;
            } else if (i == 0) {
                f = true;
            }
        }
        int sum = 0;
        if (K <= count) {
            for (int i = 0; i < A.length; i++) {
                if (i < K) {
                    sum += Math.abs(A[i]);
                } else {
                    sum += A[i];
                }
            }
        } else if ((K - count) % 2 == 1) {
            if (f) {
                for (int i = 0; i < A.length; i++) {
                    sum += Math.abs(A[i]);
                }
            }else {
                for (int i = 0; i < K; i++) {
                    A[i]= Math.abs(A[i]);
                }
                Arrays.sort(A);
                A[0]=-A[0];
                for (int i = 0; i < A.length; i++) {
                    sum += A[i];
                }
            }
        }else if ((K - count) % 2 == 0){
            for (int i = 0; i < A.length; i++) {
                sum += Math.abs(A[i]);
            }
        }

        return sum;
    }

    public static void main(String[] args) {
        System.out.println(new LC1005().largestSumAfterKNegations(new int[]{-8,3,-5,-3,-5,-2}, 6));
    }
}
